<?php
/**
 * 功能：后台商品管理控制器
 * 作者：魏安来
 * 日期：2017/01/09
 */

namespace app\index\controller;
use think\Db;
use app\index\model\Category as CategoryModel;

class Category extends Base {

	/*类别列表*/
	public function index() {
		//调用左侧菜单
		$menuController = new Menu();
		$menuController->sidebar();
		//查询一级类别
		$CategoryModel = new CategoryModel();
		$categoryInfo = $CategoryModel->oneLevelCate();
		$this->assign('categoryInfo', $categoryInfo);
		return $this->fetch();
	}

	/*添加类别*/
	public function add() {
		if (request()->isAjax()) {
			//接收数据
			$data = input('post.');
			//定义验证规则
            $rule = [
				'name' => 'require|min:2|unique:category,name='.$data['name']
            ];

            //定义错误提示信息
            $message = [
                'name.require' => '菜单名称不能为空',
				'name.min' => '菜单名称不能少于2个字符',
				'name.unique' => '菜单名称已存在'
            ];
            $validate = new \think\Validate($rule, $message);
            $result = $validate->check($data);
            if ($result) {
            	//写入数据库
				$lastId = Db::name('category')->insertGetId($data);
				if ($lastId) {
					//数据新增成功，修改类别路径path
					$path = '/'.$lastId.'/';
					$lastId = Db::name('category')->where('id',$lastId)->update(['path'=>$path]);
					if ($lastId) {
						return 'succ';
					} else {
						return 'error';
					}
				} else {
					return 'error';
				}
            } else {
            	return $this->getError();
            }
		}
		return $this->fetch();
	}

	/*类别编辑*/
	public function edit() {
		//调用左侧菜单
		$menuController = new Menu();
		$menuController->sidebar();
		$cateDate = \think\Db::name('category')->where('path','like','%/'.request()->param('id').'/%')->field('id,pid,name')->order('id asc')->select();
        $cateInfo = '';
        foreach($cateDate as $key=>$val){
        	if($key == 0){
				$cateInfo .= '{id:'.$val['id'].',pid:'.$val['pid'].',name:"'.$val['name'].'",open:true},';
        	} else{
        		$cateInfo .= '{id:'.$val['id'].',pid:'.$val['pid'].',name:"'.$val['name'].'",open:true},';
        	}
        }
        $this->assign('allcate',$cateInfo);
        $url = request()->url(true);
		if(request()->isAjax()){
    		if(input('mid') != ''){
    			/*验证同级类别是否存在,即pid和name都相同*/
    			$pid = \think\Db::name('category')->field('pid')->where('id',input('mid'))->find();
    			$dataup = [
    				'name' => input('name'),
    				'pid' => $pid['pid']
    			];
    			$rule = [
    				'name' => 'require|unique:category,name='.$dataup['name'].'&pid='.$dataup['pid'],
    			];
    			$message = [
    				'name.require' => '类别名称不能为空',
    				'name.unique' => '类别已经存在',
    			];
    			$validate = new \think\Validate($rule,$message);
    			$result = $validate->check($dataup);
    			if($result){
    				$cate = CategoryModel::get(input('mid'));
    				$cate->name = $dataup['name'];
    				$affected = $cate->save();
    				if($affected){
    					return 'succ';
    				} else{
    					return 'error';
    				}
    			} else{
    				return $this->error($validate->getError());
    			}
    		} else{
    			return '请选择需要修改的类别';
    		}
    	}
		return $this->fetch();
	}

	/*类别添加*/
	public function cateAdd() {
	    if(input('aid') != ''){
			/*验证同级类别是否存在,即pid和name都相同*/
			$pid = \think\Db::name('category')->field('pid')->where('id',input('aid'))->find();
			$path = \think\Db::name('category')->field('path')->where('id',input('aid'))->find();
			$datains = [
				'name' => input('name'),
				'pid' => input('aid')
			];
			$rule = [
				'name' => 'require|unique:category,name='.$datains['name'].'&pid='.$pid['pid']
			];
			$message = [
				'name.require' => '类别名称不能为空',
				'name.unique' => '类别已经存在'
			];
			$validate = new \think\Validate($rule,$message);
			$result = $validate->check($datains);
			if($result){
				$CategoryModel = new CategoryModel();
				$CategoryModel->name = $datains['name'];
				$CategoryModel->pid = $datains['pid'];
				$affectedins = $CategoryModel->save();
				if($affectedins){
					$res = CategoryModel::get($CategoryModel->id);
					$res->path = $path['path'].$CategoryModel->id.'/';
					$affect = $res->save();
					if($affect){
						return 'succ';
					} else{
						return 'error';
					}   					
				}
			} else{
				return $validate->getError();
			}
		} else{
			return '请填写需要添加的类别名称';
		}
	}

	/*类别删除*/
	public function delete() {
		if(input('mid') != ''){
			$cate = \think\Db::name('category')->where('pid',input('mid'))->find();
			if($cate){
				return 'hasSon';
			} else{
				$result = \think\Db::name('category')->delete(input('mid'));
				if($result){
					return 'succ';
				} else{
					return 'error';
				}
			}
		} else {
			return '请选择需要删除的类别';
		}
	}

}

?>